package org.cweili.rayminder.servlet

import org.apache.commons.lang3.StringUtils
import org.cweili.rayminder.util.Global
import org.cweili.rayminder.util.Utils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 *
 * @author Cweili
 * @version 13-8-29 下午10:02
 *
 */
class ResourceServlet extends BaseServlet {

	static final PATH = '/res'
	static final char DOT = '.'

	@Override
	protected process(HttpServletRequest req, HttpServletResponse resp) {
		def type = StringUtils.split(req.requestURI, DOT)
		type = type[type.length - 1]
		def dir
		def contentType
		def encoding
		switch (type) {
			case 'png':
				dir = 'img'
				contentType = 'image/png'
				break
			case 'jpg':
				dir = 'img'
				contentType = 'image/jpeg'
				break
			case 'gif':
				dir = 'img'
				contentType = 'image/gif'
				break
			case 'css':
				dir = 'css'
				contentType = 'text/css'
				encoding = Global.CHARSET
				break
			case 'js':
				dir = 'js'
				contentType = 'application/javascript'
				encoding = Global.CHARSET
				break
			case 'coffee':
				dir = 'coffee'
				contentType = 'application/javascript'
				encoding = Global.CHARSET
		}
		try {
			if (contentType) {
				def res = Utils.getResource(dir + req.requestURI.substring(PATH.length()))
				encoding && resp.setCharacterEncoding(encoding)
				resp.contentType = contentType
				resp.contentLength = res.length
				resp.outputStream.write(res)
			} else {
				throw new FileNotFoundException()
			}
		} catch (Exception e) {
			resp.setHeader('Content-Type', 'text/html;charset=' + Global.CHARSET)
			resp.outputStream.write(Utils.error(e))
		}
	}
}
